package com.syl.springcloud.authorization.service;

import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.syl.springcloud.authorization.constant.BaseConstant.SPLIT_SYMBOL;
import static com.syl.springcloud.authorization.constant.LoginConstant.TEST_MIMA;

/**
 * 从数据库中查询用户详情
 * @author syl
 * @create 2018-07-30 11:29
 **/
@Service
public class MyUserDetailsService implements UserDetailsService {

    /**
     * 密码为 1234
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Map<String,String> users = new HashMap<>();
        users.put("admin","ROLE_ADMIN"+SPLIT_SYMBOL+"ROLE_MANAGE");
        users.put("user","ROLE_USER");
        // 1234
        String dbUserPassword = TEST_MIMA;//数据库取出的
//        String dbRoleStr = "ROLE_ADMIN";//查询到该用户所匹配的所有角色  必须加上ROLE_前缀 否则匹配不上角色
        if(!users.containsKey(username))
            throw new UsernameNotFoundException("用户不存在！");
        return new User(username, dbUserPassword, createAuthorities(users.get(username)));
    }

    /**
     * 获取数据库角色权限
     * @param roleStr
     * @return
     */
    private List<SimpleGrantedAuthority> createAuthorities(String roleStr){
        String[] roles = roleStr.split(";");
        List<SimpleGrantedAuthority> simpleGrantedAuthorities = new ArrayList<>();
        for (String role : roles) {
            simpleGrantedAuthorities.add(new SimpleGrantedAuthority(role));
        }
        return simpleGrantedAuthorities;
    }

}
